#!/bin/bash  

# ANSI 颜色代码  
RED='\033[0;31m'  
GREEN='\033[0;32m'
BLUE='\033[0;34m'   
NC='\033[0m' # No Color 
BG_RED_WHITE='\033[41;37m'      # 红底白字, BG=background
BG_GREEN_WHITE='\033[42;37m'    # 绿底白字
BG_BLUE_WHITE='\033[46;37m'     # 蓝底白字
BG_WHITE_BLACK='\033[47;30m'    # 白底黑字

# 设置相关路径
SERVICE_DIR="$(dirname "$0")"  # 即为$
LOG_DIR="$SERVICE_DIR/log"  

# 检查日志目录是否存在，如果不存在则创建  
if [ ! -d "$LOG_DIR" ]; then  
    mkdir -p "$LOG_DIR"  
    echo "Log directory created: $LOG_DIR"  
fi 

# 设置日志文件的日期时间前缀  
DATETIME=$(date +%Y%m%d)  
LOGFILE="${LOG_DIR}/run_${ENV}_${DATETIME}.log"   
  
# 获取当前脚本名，不带路径，即secret_server.service脚本
SCRIPT_NAME=$(basename "$0")  
  
# 获取服务的名称（通常和脚本名相关）  
SERVICE_NAME=$(echo "$SCRIPT_NAME" | sed 's/^\.\///; s/\.service$//')
  
# 获取或设置PID文件的路径  
PIDFILE="${LOG_DIR}/${SERVICE_NAME}.${ENV}.pid"

# 解析传递给脚本的参数  
if [ "$#" -ne 2 ]; then  
    echo "Usage: $SCRIPT_NAME [env] {start|stop|restart|status}"  
    echo "env should be one of: prod, test, dev"  
    exit 1  
fi    

# 设置并校验环境参数  
ENV=$1  
if [[ "$ENV" != "prod" && "$ENV" != "test" && "$ENV" != "dev" ]]; then  
    echo "Invalid environment: $ENV"  
    echo "env should be one of: prod, test, dev"
    exit 1  
fi   


# 获取服务的实际PID  
get_pid() {
    pid=$(ps -ef | grep "python server/server.py -e $ENV" | grep -v grep | awk '{print $2}')
    echo $pid
}  

# 查询服务状态
status() {
    PID=$(get_pid)
    # -z条件测试操作符，如果检查的串为空串（这里指PID不存在），则返回true，否则为false
    if [ -z "$PID" ]; then
        echo -e "Service '$SERVICE_NAME' in environment '$ENV' ${BG_RED_WHITE}is not running$NC."
    else   
        echo -e "Service '$SERVICE_NAME' ${GREEN}(PID "$PID")$NC in environment '$ENV' ${BG_GREEN_WHITE}is already running$NC." 
    fi 
}

# 启动服务  
start() {  
    PID=$(get_pid)
    # 使用kill -0 $pid 来检查进程是否存在，存在返回true，否则为false
    if kill -0 $PID 2>/dev/null; then  
        echo -e "Service '$SERVICE_NAME' ${GREEN}(PID "$PID")$NC in environment '$ENV' ${BG_GREEN_WHITE}is already running$NC." 
        return 1  
    fi 
    echo "Starting service '$SERVICE_NAME' in environment '$ENV' ..."
    # 运行日志改为追加到文件  
    nohup python server/server.py -e "$ENV" >> "$LOGFILE" 2>&1  & 
    sleep 1
    newpid=$(get_pid) 
    echo $newpid > "$PIDFILE" 
    echo -e "Service '$SERVICE_NAME' ${GREEN}(New PID "$newpid")$NC in environment '$ENV' ${BG_GREEN_WHITE}has been started success$NC."  
}  
  
# 停止服务  
stop() {  
    PID=$(get_pid)   
    if [ -z "$PID" ]; then  
        echo -e "Service '$SERVICE_NAME' in environment '$ENV' ${BG_RED_WHITE}is not running$NC."  
        return 1  
    fi 
  
    # 发送SIGTERM信号  
    kill "$PID"  
      
    # 等待PID文件中指定的进程完全终止  
    while kill -0 "$PID" 2>/dev/null; do  
        echo -e "Waiting for service '$SERVICE_NAME' ${GREEN}(PID $PID)$NC in environment '$ENV' to stop ..."  
        sleep 1  
    done  
  
    echo -e "service '$SERVICE_NAME' ${GREEN}(PID $PID)$NC in environment '$ENV' ${BG_RED_WHITE}has been stopped$NC."  
    rm -f "$PIDFILE"  
}  
  
# 重启服务  
restart() {  
    stop  
    start  
}  

    
case "$2" in  
    start)  
        start  
        ;;  
    stop)  
        stop  
        ;;  
    restart)  
        restart  
        ;;
    status)
        status
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status} [env]"  
        echo "env should be one of: prod, test, dev"   
        ;;  
esac  
  
exit 0